import React from "react";
import { connect } from "react-redux";
import { messages } from "share/common";
import { Form, Radio, Icon, Row, Col, Button, Badge, Popconfirm } from "antd";
import SlideFrame from "components/slide-frame";
import "styles/setting/workflow-config/workflow-config.scss";
import NewWorkFlowConfig from "containers/application-setting/new-fp-setting";
import WorkFlowConfigDefault from "containers/application-setting/default-fp-setting";
import workflowConfigData from "containers/setting/workflow-config/work-flow-config-data";
import workflowConfigService from "containers/setting/workflow-config/workflow-config.service";
import AdvancedTable from "components/advanced-table";
import errorMessage from "share/errorMessage";
import Priority from "components/template/priority";
import Info from "components/info";

const RadioGroup = Radio.Group;
const SimpleTable = AdvancedTable.SimpleTable;
const options = [
  { label: messages("common.all") /*全部*/, value: "ALL" },
  { label: messages("request-4.key553") /*租户*/, value: "TENANT" },
  { label: messages("request-4.key12") /*公司*/, value: "COMPANY" },
];
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 },
};
class AgencySettingConfig extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowKey: "agency-setting",
      slideShow: false,
      title: "",
      nowMode: "create",
      nowConfig: [],
      tableConfig: {
        columns: [
          {
            dataIndex: "levelCode",
            title: messages("request-4.key554") /*层级*/,
            width: 120,
            minWidth: 100,
            render: (text) => {
              return (
                <span>
                  {text === "COMPANY" ? messages("request-4.key12") /*公司*/ : messages("request-4.key553") /*租户*/}
                </span>
              );
            },
          },
          {
            dataIndex: "levelOrgName",
            title: messages("request-4.key555") /*所属组织*/,
            render: (text) => text || "-",
          },
          {
            dataIndex: "enabled",
            title: messages("common.column.status") /*状态*/,
            maxWidth: 120,
            width: 100,
            minWidth: 80,
            render: (text) => {
              return (
                <span>
                  <Badge status={text ? "success" : "error"} />
                  {text ? messages("common.status.enable") /*启用*/ : messages("request-4.key227") /*禁用temp*/}
                </span>
              );
            },
          },
          {
            title: messages("common.operation") /*操作*/,
            dataIndex: "delete",
            width: 120,
            minWidth: 120,
            render: (value, record) =>
              !record.readOnly && (
                <Popconfirm
                  placement="bottomRight"
                  title={messages("request-4.key556") /*您确定删除这条规则吗？*/}
                  onConfirm={(e) => this.handleDelete(e, record)}
                >
                  <a
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                    }}
                  >
                    {messages("common.delete") /*删除*/}
                  </a>
                </Popconfirm>
              ),
          },
        ],
        searchForm: [
          {
            id: "levelCode",
            initialValue: "ALL",
            label: messages("request-4.key554") /*层级*/,
            component: <RadioGroup options={options} initialValue="ALL" />,
            tagParser: (value) => this.getLevelTypeValue(value),
            dataIndex: "levelCode",
          },
          {
            id: "levelOrgId",
            dataIndex: "levelOrgName",
            label: messages("request-4.key555") /*所属组织*/,
            parser: (value) => ({
              levelOrgId: value ? value.rangeValue.id : null,
            }),
            tagParser: (value) => value && value.rangeValue.name,
            component: (
              <Priority
                style={{ marginLeft: 0 }}
                formItemLayout={formItemLayout}
                top="TENANT"
                onlyCompany
                showCompanyComponent={false}
                showCompany
                companyProps={{
                  single: true,
                }}
              />
            ),
          },
        ],
      },
    };
  }

  componentDidMount() {
    const { nowKey } = this.state;
    this.setState({
      nowConfig: workflowConfigData[nowKey].configs,
    });
  }

  getLevelTypeValue(type) {
    let text = messages("common.all"); /*全部*/
    switch (type) {
      case "TENANT":
        text = messages("request-4.key553") /*租户*/;
        break;
      case "COMPANY":
        text = messages("request-4.key12") /*公司*/;
        break;
    }
    return text;
  }

  afterCloseSlideFrame = (flag) => {
    if (flag) {
      this.advancedTableRef.getList();
    }
  };

  handleDelete = (e, record) => {
    e.stopPropagation();
    const { nowKey } = this.state;
    const apiObj = {
      "agency-setting": workflowConfigService.deleteProxyConfig,
    };
    const paramsKey = {
      "agency-setting": "id",
    };
    apiObj[nowKey]({ [paramsKey[nowKey]]: record[paramsKey[nowKey]] })
      .then((res) => {
        this.advancedTableRef.getList();
      })
      .catch((e) => {
        errorMessage(e.response);
      });
  };

  service = (page, size, searchParams, extraParams) => {
    const { nowKey } = this.state;
    const apiObj = {
      "agency-setting": workflowConfigService.getProxyConfigList,
    };
    if (searchParams.levelCode === "ALL") {
      searchParams.levelCode = "";
    }
    return apiObj[nowKey]({ page, size, ...searchParams });
  };

  handleCreate = (title, nowMode, id = null) => {
    const { nowKey } = this.state;
    let pageFile = NewWorkFlowConfig;
    let apiService = "";
    let saveApiService = "";
    //配置接口
    const apiObj = {
      "agency-setting": {
        apiService: workflowConfigService.getProxyDefaultConfig,
        editApiService: workflowConfigService.getProxyConfigDetail,
        saveApiService: workflowConfigService.postProxyConfig,
      },
    };
    switch (nowMode) {
      case "create":
        pageFile = NewWorkFlowConfig;
        apiService = apiObj[nowKey].apiService;
        saveApiService = apiObj[nowKey].saveApiService;
        break;
      case "default":
        pageFile = WorkFlowConfigDefault;
        apiService = apiObj[nowKey].apiService;
        break;
      case "edit":
        pageFile = NewWorkFlowConfig;
        apiService = apiObj[nowKey].editApiService;
        saveApiService = apiObj[nowKey].saveApiService;
        break;
    }
    SlideFrame.open(
      {
        title: title,
        content: pageFile,
        afterClose: this.afterCloseSlideFrame,
        width: "800px",
        params: {
          id,
          apiService,
          saveApiService,
          configFp: workflowConfigData[nowKey].configs,
        },
      },
      this
    );
  };

  render() {
    const { nowKey, tableConfig } = this.state;
    const infoData = {
      dataSource: { explain: workflowConfigData[nowKey].description },
      attributes: [
        {
          title: messages("expense-8.key6") /*说明*/,
          dataIndex: "explain",
          span: 24,
        },
      ],
    };
    const attributes =
      infoData &&
      infoData.attributes &&
      infoData.attributes.map((i) => {
        i.widthFix = false;
        return i;
      });
    return (
      <div>
        {infoData && <Info paragraph dataSource={infoData.dataSource} attributes={attributes} />}
        <SimpleTable
          onRef={(ref) => (this.advancedTableRef = ref)}
          style={{ marginTop: 10 }}
          {...tableConfig}
          onRow={(record) => ({
            onClick: () => this.handleCreate("编辑", "edit", record.id),
          })}
          rowKey="id"
          onGetDataError={(e) => errorMessage(e.response)}
          service={this.service}
          tableName="agency-setting-config-table"
        >
          <Row type="flex" className="table-header-buttons" justify="space-between" align="middle">
            <Col span={12}>
              <Button type="primary" onClick={() => this.handleCreate(messages("common.create") /*新建*/, "create")}>
                {messages("common.create") /*新建*/}
              </Button>
            </Col>
            <Col span={12} className="default-btn">
              <div
                className="default-btn-text"
                onClick={() => this.handleCreate(messages("request-4.key561") /*默认规则*/, "default")}
              >
                <Icon type="file-text" style={{ marginRight: 5 }} />
                {messages("request-4.key561") /*默认规则*/}
              </div>
            </Col>
          </Row>
        </SimpleTable>
      </div>
    );
  }
}

AgencySettingConfig.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    language: state.main.language,
  };
}

const wrappedWorkflowConfig = Form.create()(AgencySettingConfig);

export default connect(mapStateToProps)(wrappedWorkflowConfig);
